package com.cloud.pdd.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.cloud.pdd.config.Config;
import com.cloud.pdd.model.domain.ProductUrlGenRequest;
import com.cloud.pdd.model.enums.RedisKey;
import com.cloud.pdd.model.request.PddProductInfoRequest;
import com.cloud.pdd.model.request.PddProductSearchRequest;
import com.cloud.pdd.model.request.PddProductRecommendListRequest;
import com.cloud.pdd.service.PddProductService;
import com.cloud.pdd.service.PddUsersService;
import com.cloud.pdd.util.PddUtil;
import com.cloud.redis.config.RedisUtils;
import com.pdd.pop.sdk.common.util.JsonUtil;
import com.pdd.pop.sdk.http.PopClient;
import com.pdd.pop.sdk.http.api.pop.request.*;
import com.pdd.pop.sdk.http.api.pop.response.*;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@AllArgsConstructor
public class PddProductServiceImpl implements PddProductService {
    private final PddCommonServiceImpl pddCommonService;
    private final Config config;
    private final PddUsersService pddUsersService;
    private final PddUtil pddUtil;
    private final RedisUtils redisUtils;

    //    多多进宝商品查询
    //    https://open.pinduoduo.com/application/document/api?id=pdd.ddk.goods.search&permissionId=2
    @SneakyThrows
    @Override
    public PddDdkGoodsSearchResponse.GoodsSearchResponse getProductSearch(PddProductSearchRequest req) {
        req.setPage(req.getPage() == null ? 1 : req.getPage());
        req.setPageSize(req.getPageSize() == null ? 10 : req.getPageSize());
        PopClient client = pddCommonService.getClient();
        PddDdkGoodsSearchRequest request = new PddDdkGoodsSearchRequest();
        BeanUtil.copyProperties(req, request);
        if (req.getOptId() != null) {
            request.setOptId(req.getOptId());
        }
        request.setPage(req.getPage());
        request.setPageSize(req.getPageSize());
        request.setKeyword(req.getKeyword());
        request.setCustomParameters(pddUtil.getCustomParameters());
        PddDdkGoodsSearchResponse response = client.syncInvoke(request);
        PddDdkGoodsSearchResponse.GoodsSearchResponse goodsSearchResponse = response.getGoodsSearchResponse();
        return goodsSearchResponse;
    }

    //    多多进宝商品详情查询
    //    https://open.pinduoduo.com/application/document/api?id=pdd.ddk.goods.detail&permissionId=2
    @SneakyThrows
    @Override
    public PddDdkGoodsDetailResponse.GoodsDetailResponse getProductDetail(PddProductInfoRequest req) {
        PopClient client = pddCommonService.getClient();
        PddDdkGoodsDetailRequest request = new PddDdkGoodsDetailRequest();
        request.setCustomParameters(pddUtil.getCustomParameters());
        request.setGoodsSign(req.getGoodsId());
        request.setPid(config.getPddPid());
        request.setSearchId(req.getSearchId());
        request.setCustomParameters(pddUtil.getCustomParameters());
        PddDdkGoodsDetailResponse response = client.syncInvoke(request);
        PddDdkGoodsDetailResponse.GoodsDetailResponse goodsDetailResponse = response.getGoodsDetailResponse();
        return goodsDetailResponse;
    }

    //    多多进宝推广链接生成
    //    https://open.pinduoduo.com/application/document/api?id=pdd.ddk.goods.promotion.url.generate&permissionId=2
    @SneakyThrows
    @Override
    public PddDdkGoodsPromotionUrlGenerateResponse.GoodsPromotionUrlGenerateResponse getProductPromotionUrlGenerate(
            PddDdkGoodsPromotionUrlGenerateRequest request) {
        PopClient client = pddCommonService.getClient();
//        PddDdkGoodsPromotionUrlGenerateRequest request = new PddDdkGoodsPromotionUrlGenerateRequest();
        request.setCustomParameters(pddUtil.getCustomParameters());
        request.setGenerateAuthorityUrl(false);
        request.setGenerateMallCollectCoupon(false);
        request.setGenerateQqApp(true);
        request.setGenerateSchemaUrl(true);
        request.setGenerateShortUrl(true);
        request.setGenerateWeApp(true);
        //rue--生成多人团推广链接 false--生成单人团推广链接（默认false）
        // 1、单人团推广链接：用户访问单人团推广链接，可直接购买商品无需拼团。
        // 2、多人团推广链接：用户访问双人团推广链接开团，若用户分享给他人参团，则开团者和参团者的佣金均结算给推手
//        request.setMultiGroup(true);
        request.setPId(config.getPddPid());
        PddDdkGoodsPromotionUrlGenerateResponse response = client.syncInvoke(request);
        PddDdkGoodsPromotionUrlGenerateResponse.GoodsPromotionUrlGenerateResponse goodsPromotionUrlGenerateResponse = response.getGoodsPromotionUrlGenerateResponse();
        return goodsPromotionUrlGenerateResponse;
    }

    //    多多进宝转链接口
//    https://open.pinduoduo.com/application/document/api?id=pdd.ddk.goods.zs.unit.url.gen&permissionId=2
    @SneakyThrows
    @Override
    public PddDdkGoodsZsUnitUrlGenResponse.GoodsZsUnitGenerateResponse getProductUnitUrlGenerate(
            HttpServletRequest httpServletRequest, ProductUrlGenRequest req) {
        PopClient client = pddCommonService.getClient();
        PddDdkGoodsZsUnitUrlGenRequest request = new PddDdkGoodsZsUnitUrlGenRequest();
        request.setCustomParameters(pddUtil.getCustomParameters());
        request.setPid(config.getPddPid());
        request.setSourceUrl(req.getSourceUrl());
        PddDdkGoodsZsUnitUrlGenResponse response = client.syncInvoke(request);
        PddDdkGoodsZsUnitUrlGenResponse.GoodsZsUnitGenerateResponse goodsZsUnitGenerateResponse = response.getGoodsZsUnitGenerateResponse();
        return goodsZsUnitGenerateResponse;
    }

    //查询商品标签列表
//    https://open.pinduoduo.com/application/document/api?id=pdd.goods.opt.get&permissionId=2
    @SneakyThrows
    @Override
    public PddGoodsOptGetResponse.GoodsOptGetResponse getProductOpt() {
        PopClient client = pddCommonService.getClient();
        PddGoodsOptGetRequest request = new PddGoodsOptGetRequest();
        request.setParentOptId(0);
        PddGoodsOptGetResponse response = client.syncInvoke(request);
        PddGoodsOptGetResponse.GoodsOptGetResponse goodsOptGetResponse = response.getGoodsOptGetResponse();
        return goodsOptGetResponse;
    }

    //    多多进宝商品推荐API
//    https://open.pinduoduo.com/application/document/api?id=pdd.ddk.goods.recommend.get&permissionId=2
    @SneakyThrows
    @Override
    public PddDdkGoodsRecommendGetResponse.GoodsBasicDetailResponse getProductRecommend(PddProductRecommendListRequest req) {
        String activity = StrUtil.join("_", req.getActivityTags());
        String key = config.getRedisVersion() + "_" + RedisKey.pddRecommendKey +
                "_" + req.getChannelType() + "_" + req.getCatId() + "_" + activity + "_" + req.getLimit();
        String o = Convert.toStr(redisUtils.get(key), "");
        if (!StrUtil.isEmpty(o)) {
            return JsonUtil.transferToObj(o, PddDdkGoodsRecommendGetResponse.GoodsBasicDetailResponse.class);
        }
        PopClient client = pddCommonService.getClient();
        PddDdkGoodsRecommendGetRequest request = new PddDdkGoodsRecommendGetRequest();
        if (req.getActivityTags() != null) {
            request.setActivityTags(req.getActivityTags());
        }
        if (req.getCatId() != null) {
            request.setCatId(req.getCatId());
        }
        if (req.getChannelType() != null) {
            request.setChannelType(req.getChannelType());
        }
//        request.setCustomParameters("str");
//        List<String> goodsSignList = new ArrayList<String>();
//        goodsSignList.add("str");
//        request.setGoodsSignList(goodsSignList);
        if (req.getLimit() != null) {
            request.setLimit(req.getLimit());
        }
//        if (req.getListId() != null) {
//            request.setListId(req.getListId());
//        }
//        if (req.getOffset() != null) {
//            request.setOffset(req.getOffset());
//        }
        request.setPid(config.getPddPid());
        request.setCustomParameters(pddUtil.getCustomParameters());
        PddDdkGoodsRecommendGetResponse response = client.syncInvoke(request);
        PddDdkGoodsRecommendGetResponse.GoodsBasicDetailResponse goodsBasicDetailResponse = response.getGoodsBasicDetailResponse();
//        String s = JSONUtil.toJsonStr(goodsBasicDetailResponse);
        String s = JsonUtil.transferToJson(goodsBasicDetailResponse);
        redisUtils.set(key, s, 6, TimeUnit.HOURS);
        return goodsBasicDetailResponse;
    }

//    @Override
//    public PddDdkGoodsRecommendGetResponse.GoodsBasicDetailResponse getProductGfbp(PddProductRecommendListRequest pddProductRecommendListRequest) {
//        List<Integer> activityTags = new ArrayList<Integer>();
//        activityTags.add(ProductActivityTagsEnum.JINGXUANBAOPINGF.getCode());
//        pddProductRecommendListRequest.setActivityTags(activityTags);
//        PddDdkGoodsRecommendGetResponse.GoodsBasicDetailResponse productRecommend = this.getProductRecommend(pddProductRecommendListRequest);
//        return productRecommend;
//    }

    @SneakyThrows
    @Override
    public void setProductPidGenerate(Long mediaId) {
        PopClient client = pddCommonService.getClient();
        PddDdkGoodsPidGenerateRequest request = new PddDdkGoodsPidGenerateRequest();
        request.setNumber(10L);
        List<String> pIdNameList = new ArrayList<String>();
        pIdNameList.add(config.getPddPid());
        request.setPIdNameList(pIdNameList);
        request.setMediaId(mediaId);
        PddDdkGoodsPidGenerateResponse response = client.syncInvoke(request);
        PddDdkGoodsPidGenerateResponse.PIdGenerateResponse pIdGenerateResponse = response.getPIdGenerateResponse();
//        System.out.println(JsonUtil.transferToJson(response));
    }

    private String oneList(PddDdkGoodsSearchResponse.GoodsSearchResponseGoodsListItem item) {
        StringBuilder sb = new StringBuilder();
        String detailUrl = pddUtil.getDetailUrl(item.getGoodsSign(), item.getSearchId());
        Long price = item.getMinGroupPrice() - item.getCouponDiscount();
        sb.append("<li>");
        sb.append("<a href=\"" + detailUrl + "\"><i><img src=\"" + item.getGoodsThumbnailUrl() + "\" ></i></a>");
        sb.append("<dl>");
        sb.append("<dt><a href=\"" + detailUrl + "\">" + item.getGoodsName() + "</a></dt>");
        sb.append("<dd>￥" + pddUtil.getPrice(price) + "</dd>");
        sb.append("<p><b>已售 " + item.getSalesTip() + "</b></p>");
        sb.append("<i onclick=\"window.location.href='" + detailUrl + "';\"></i>");
        sb.append("</dl></li>");
        return sb.toString();
    }

    private String twoList(PddDdkGoodsSearchResponse.GoodsSearchResponseGoodsListItem item) {
        StringBuilder sb = new StringBuilder();
        String detailUrl = pddUtil.getDetailUrl(item.getGoodsSign(), item.getSearchId());
        Long price = item.getMinGroupPrice() - item.getCouponDiscount();
        sb.append("<li>");
        sb.append("<a href=\"" + detailUrl + "\"><i>");
        sb.append("<img src=\"" + item.getGoodsThumbnailUrl() + "\"></i></a>");
        sb.append("<p><a href=\"" + detailUrl + "\" >" + item.getGoodsName() + "</a></p>");
        sb.append("<span>");
        sb.append("<em>￥" + pddUtil.getPrice(price) + "</em>");
        sb.append("<i onclick=\"window.location.href='" + detailUrl + "';\"></i>");
        sb.append("</span></li>");
        return sb.toString();
    }

    @Override
    public String getProductListData(
            PddProductSearchRequest req,
            List<PddDdkGoodsSearchResponse.GoodsSearchResponseGoodsListItem> goodsList) {
        StringBuilder sb = new StringBuilder();
        Integer showType = req.getShowType();
        if (showType == null) {
            showType = 2;
        }
        if (goodsList == null) {
            return "";
        }
        for (PddDdkGoodsSearchResponse.GoodsSearchResponseGoodsListItem item : goodsList) {
            if (showType == 1) {
                sb.append(oneList(item));
            } else {
                sb.append(twoList(item));
            }
        }
        return sb.toString();
    }
}
